package shia.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class ConnectionUtil {

    private static final String CONFIG_FILE = "config.properties";

    private static String driverName;

    private static String connectionURL;

    private static final Logger LOGGER = LoggerFactory.getLogger(ConnectionUtil.class);
    static {
        try {
            InputStream inputStream = new BufferedInputStream(ConnectionUtil.class.getClassLoader().getResourceAsStream(CONFIG_FILE));
            //InputStream inputStream = new BufferedInputStream(new FileInputStream(System.getProperty("user.dir") + CONFIG_FILE));
            Properties properties = new Properties();
            properties.load(inputStream);

            driverName = properties.getProperty("jdbc.driverClassName");
            connectionURL = properties.getProperty("jdbc.connectURL");
        } catch (FileNotFoundException e) {
            LOGGER.error("get config properties exception:", e);
        } catch (IOException e) {
            LOGGER.error("get config properties exception:", e);
        }
    }

    static {
        try {
            Class.forName(driverName).newInstance();
        } catch (ClassNotFoundException e) {
            LOGGER.error("register db driver exception:", e);
        } catch (InstantiationException e) {
            LOGGER.error("register db driver exception:", e);
        } catch (IllegalAccessException e) {
            LOGGER.error("register db driver exception:", e);
        }
    }

    public static Connection getConnection() {
        Connection connection = null;

        try {
            connection = DriverManager.getConnection(connectionURL);
        } catch (SQLException e) {
            LOGGER.error("get db connection exception:", e);
        }

        return connection;
    }

    public static void freeResources(PreparedStatement preparedStatement, Connection connection) {
        try {
            if (preparedStatement != null) {
                preparedStatement.close();
            }

            if (connection != null) {
                connection.close();
            }
        } catch(SQLException e) {
            LOGGER.error("free db resources exception:", e);
        }
    }
}
